package cn.cutie.clot.mq.server;

import cn.cutie.clot.mq.model.ClotMessage;
import cn.cutie.clot.mq.model.Result;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Description:
 * @Author: Cutie
 * @CreateDate: 2024/7/10 10:13
 * @Version: 0.0.1
 */
@RestController
@RequestMapping("/clotmq")
public class MQServer {

    @RequestMapping("/test")
    public Result test(){
        return Result.ok();
    }

    // send
    @RequestMapping("/send")
    public Result<String> send(@RequestParam("t") String topic,
                               @RequestBody ClotMessage<String> message){
        int send = MessageQueue.send(topic, message);
        return Result.ok("" + send);
    }

    // recv
    @RequestMapping("/recv")
    public Result<ClotMessage<?>> recv(@RequestParam("t") String topic,
                                       @RequestParam("cid") String consumerId){
        ClotMessage<?> recv = MessageQueue.recv(topic, consumerId);
        return Result.msg(recv);
    }

    // recv
    @RequestMapping("/batch")
    public Result<List<ClotMessage<?>>> batch(@RequestParam("t") String topic,
                                             @RequestParam("cid") String consumerId,
                                             @RequestParam(name = "size", defaultValue = "1000") int size){
        List<ClotMessage<?>> batch = MessageQueue.batch(topic, consumerId, size);
        return Result.msg(batch);
    }

    // ack
    @RequestMapping("/ack")
    public Result<String> ack(@RequestParam("t") String topic,
                              @RequestParam("cid") String consumerId,
                              @RequestParam("offset") Integer offset){
        int ack = MessageQueue.ack(topic, consumerId, offset);
        return Result.ok("" + ack);
    }

    // sub
    @RequestMapping("/sub")
    public Result<String> sub(@RequestParam("t") String topic, @RequestParam("cid") String consumerId){
        MessageQueue.sub(new MessageSubscription(topic, consumerId, -1));
        return Result.ok();
    }

    // unsub
    @RequestMapping("/unsub")
    public Result<String> unsub(@RequestParam("t") String topic, @RequestParam("cid") String consumerId){
        MessageQueue.unSub(new MessageSubscription(topic, consumerId, -1));
        return Result.ok();
    }
}
